package com.lwb.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lwb.eduservice.entity.EduSubject;
import com.lwb.eduservice.entity.excel.ExcelSubjectData;
import com.lwb.eduservice.entity.excel.OneSubject;
import com.lwb.eduservice.entity.excel.TwoSubject;
import com.lwb.eduservice.listener.SubjectExcelListener;
import com.lwb.eduservice.mapper.EduSubjectMapper;
import com.lwb.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-11-16
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void addSubject(MultipartFile file, EduSubjectService eduSubjectService) {
        try {
            //文件输入流
            InputStream in = file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(in, ExcelSubjectData.class,new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> findAllSubject() {
        //查询到所有的一级分类
        QueryWrapper<EduSubject> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("parent_id","0");
        List<EduSubject> eduSubject1 = baseMapper.selectList(queryWrapper1);

        //查询到所有的二级分类
        QueryWrapper<EduSubject> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.ne("parent_id","0");
        List<EduSubject> eduSubject2 = baseMapper.selectList(queryWrapper2);

        //创建一级分类
        List<OneSubject> oneSubjects = new ArrayList<>();
        //封装一级分类，并且将二级分类封装到一级分类中
        for (int i=0;i<eduSubject1.size();i++){
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(eduSubject1.get(i),oneSubject);

            //创建二级分类
            List<TwoSubject> twoSubjects = new ArrayList<>();
            //将二级分类封装到一级分类中
            for(int j=0;j<eduSubject2.size();j++){
                TwoSubject twoSubject = new TwoSubject();
                if(oneSubject.getId().equals(eduSubject2.get(j).getParentId())){
                    BeanUtils.copyProperties(eduSubject2.get(j),twoSubject);
                    twoSubjects.add(twoSubject);
                }
            }
            oneSubject.setChildren(twoSubjects);
            oneSubjects.add(oneSubject);
        }
        return oneSubjects;
    }
}
